<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\models\user\EmailToken;
use App\other\TokenType;
use App\other\UtilsClass;
use App\models\user\User;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\Request;
use Validator;

class ForgotPasswordController extends Controller
{
    public function resetPw(Request $request){
        $validator = Validator::make($request->all(),[
            'id'    => 'required|integer|exists:email_tokens,id',
            'token' => 'required|min:32|max:32|exists:email_tokens,token'
        ]);

        if ($validator->fails()){
            return redirect('/password/reset')->with(['_error' => 'Token验证失败']);
        }

        $token = EmailToken::where('id', $request->get('id'))
            ->where('token', $request->get('token'))
            ->where('dead_time', '>=', time())->first();
        if (empty($token) || $token->type != TokenType::TOKEN_PASSWDRESET_TYPE){
            return redirect('/login')->with(['_error' => '无法验证邮箱或已过期']);
        }

        $user = User::find($token->uid);
        if (empty($user)){
            return redirect('/login')->with(['_error' => '验证用户失败']);
        }

        $input          = $request->all();
        $input['email'] = $user->email;
        return view('auth.resetpw', compact('input'));


    }

    public function setPassword(Request $request){
        $validator = Validator::make($request->all(),[
            'id'        => 'required|integer|exists:email_tokens,id',
            'token'     => 'required|min:32|max:32|exists:email_tokens,token',
            'password'  => 'required|min:8|confirmed',
        ]);

        if ($validator->fails()){
            return redirect()->back()->with(['_error' => UtilsClass::arrayToStringForItem($validator->getMessageBag()->getMessages())]);
        }

        $token  = EmailToken::find($request->get('id'));
        $user   = User::find($token->uid);
        if (empty($user)){
            return redirect('/password/reset')->with(['_error' => '用户验证失败']);
        }
        $user->password = bcrypt($request->get('password'));
        $user->save();
        EmailToken::destroy($token->id);
        return redirect('/login')->with(['status' => '密码修改成功']);
    }

    public function __construct(){
        $this->middleware('guest');
    }
}
